<!--
 @Author: libing/makeup1122
 @Email: makeup1123@163.com
 @Date: "2020-04-03 20:38:50"
-->
<template>
  <v-menu offset-y :close-on-content-click="false" v-model="menuValue" allow-overflow max-width="600">
    <template v-slot:activator="{ on }">
      <v-text-field
        :loading="loading"
        :disabled="loading"
        v-bind="$attrs"
        :autocomplete="false"
        v-on="on"
        :value="selected"
        >
        <template v-slot:append-outer>
          <slot name="append-outer"></slot>
        </template>
        </v-text-field>
    </template>
    <!-- <v-card> -->
    <v-treeview
      class="white"
      :loading="loading"
      :items="items"
      :active="[value]"
      :selectable="multiple"
      :return-object="returnObject"
      max-width="100%"
      item-text="name"
      activatable
      item-key="cid"
      @input="inputHandle"
      @update:active="activeHandle"
      open-on-click
      open-all
      hoverable
      dense
    ></v-treeview>
    <!-- </v-card> -->
  </v-menu>
</template>
<script>
export default {
  name: 'TreeSelect',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    items: {
      type: Array,
      default: () => { return [] }
    },
    value: {
      type: [Number, Array, Object]
    },
    returnObject: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  components: {},
  data: function () {
    return {
      menuValue: false
    }
  },
  computed: {
    cidArray: function() {
      if (this.multiple) {
        return (this.returnObject && this.value !== null) ? this.value.map(e => e.cid) : this.value
      } else {
        return (this.returnObject && this.value !== null) ? [this.value.cid] : [this.value]
      }
    },
    selected: function() {
      let text = []
      // 递归遍历
      function findByCid(arr, cid) {
        if (!Array.isArray(arr) || cid === null) return ''
        for (const e of arr) {
          if (cid.includes(e.cid)) {
            // return e.name
            text.push(e.name)
          }
          if (Array.isArray(e.children)) {
            findByCid(e.children, cid)
            // if (t !== undefined) return t
          }
        }
      }
      findByCid(this.items, this.cidArray)
      return text.join(',')
    }
  },
  methods: {
    inputHandle: function(active) {
      if (this.multiple && active.length > -1) {
        this.$emit('input', active)
      }
    },
    activeHandle: function(active) {
      if (!this.multiple && active.length === 1) {
        this.$emit('input', active[0])
        this.menuValue = false
      }
    }
  }
}
</script>
<style scoped>
</style>
